<template>
  <view v-if="c.state.isCreated" :class="viewClassNames">
    <IBizViewLayoutPanel
      v-if="!c.state.hasError"
      :container="c"
      :params="c.params"
      :context="c.context"
      :controls="controls"
      :modelData="viewLayoutPanel"
      :provider="c.providers[viewLayoutPanel.name]"
      @controllerAppear="onLayoutPanelCreated"
    ></IBizViewLayoutPanel>
  </view>
</template>

<script setup lang="ts">
import { IAppView } from '@ibiz/model-core'
import {
  ViewController,
  IModal,
  IViewProvider,
  IViewLayoutPanelController,
  getControlsByView,
} from '@ibiz-template/runtime'
import { useNamespace, useViewController } from '@/use'

const props = defineProps({
  context: Object as PropType<IContext>,
  params: { type: Object as PropType<IParams>, default: () => ({}) },
  modelData: { type: Object as PropType<IAppView>, required: true },
  modal: { type: Object as PropType<IModal> },
  state: { type: Object as PropType<IData> },
  provider: { type: Object as PropType<IViewProvider> },
})

const ns = useNamespace('view')
const c = useViewController((...args) => new ViewController(...args))

const controls = computed(() => {
  return getControlsByView(c.model).map((ctrl) => {
    const slotKey = ctrl.name || ctrl.id
    return {
      modelData: ctrl,
      slotProps: c.slotProps[slotKey] || {},
    }
  })
})

const { viewType, sysCss, codeName, viewLayoutPanel } = c.model

const onLayoutPanelCreated = (controller: IViewLayoutPanelController): void => {
  c.setLayoutPanel(controller)
}

const viewClassNames = computed(() => [
  ns.b(),
  ns.b(viewType.toLowerCase()),
  ns.m(codeName),
  sysCss?.cssName ? sysCss?.cssName : '',
  c.state.viewMessages.TOP ? 'has-top-message' : '',
  c.state.viewMessages.BOTTOM ? 'has-bottom-message' : '',
])
</script>
